<template>
  <div class="container">
    <transition :name="routerAni">
      <router-view
        @selectCompanyCallBack="selectCompanyCallBack"
        @selectDepCallBack="selectDepCallBack"
        class="router-view of-y-s">
      </router-view>
    </transition>
    <div class="box box-ver w-p100 h-p100">
      <div class="box-f1 of-y-s content">
        <div v-for="(item, index) in entrys" :value="item" :key="index" class="item">
          <div class="head box box-ac">
            <div class="">{{item.userName}}</div>
            <div class="box-f1 tx-r city">{{item.from}}-{{item.to}}</div>
          </div>
          <div class="line box box-ac">
            <div>出差日期</div>
            <div class="box-f1 tx-r tc-999">{{formatTime(item)}}</div>
          </div>
          <div class="line box box-ac">
            <div>出差补助标准</div>
            <input v-limit-money="{max: item.MaxCCBZ}" :readonly="readonly" v-model="item.EventionSubsidy" type="number" placeholder="请输入" class="box-f1 tx-r tc-333" />
            <div class="icon icon-edit"></div>
          </div>
          <div class="line box box-ac">
            <div>住宿标准</div>
            <input v-limit-money="{max: item.MaxZSBZ}" :readonly="readonly" v-model="item.HotelExpense" type="number" placeholder="请输入" class="box-f1 tx-r tc-333" />
            <div class="icon icon-edit"></div>
          </div>
          <div class="line box box-ac">
            <div>出行标准</div>
            <div class="box-f1 tx-r tc-999">机票经济舱或高铁二等座</div>
            <div class="icon icon-edit opa-0"></div>
          </div>
          <div @click="selectCompany(index)" class="line box box-ac">
            <div>所属公司</div>
            <div class="box-f1 tx-r tc-333 ell">{{item.companyName}}</div>
            <div class="icon icon-edit"></div>
          </div>
          <div @click="selectDep(index)" class="line box box-ac">
            <div>所属部门</div>
            <div class="box-f1 tx-r tc-333 ell">{{item.depName}}</div>
            <div class="icon icon-edit"></div>
          </div>
        </div>
      </div>
      <div class="bottom box box-ac">
        <div v-if="!bizAccountBill.state || bizAccountBill.state == 20" @click="handleSubmit(0)" class="btn box box-f1 box-ac box-jc w-p100">暂存草稿</div>
        <div v-if="bizAccountBill.state == 25" @click="abandonNewBills()" class="btn box box-f1 box-ac box-jc w-p100">废弃</div>
        <div @click="handleSubmit(1)" class="btn box box-f1 box-ac box-jc w-p100">发起K2</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { formatDate, countDate, getBillConfig, getJMByBillNum } from '@/assets/js/common'
import { abandonNewBills, getTravelTripStandards } from '@/assets/js/api'
export default {
  name: 'xinCenStep3',
  data () {
    return {
      entrys: []
    }
  },
  computed: {
    ...mapState(['userNum', 'userInfo', 'bizAccountBill', 'routerAni']),
    readonly () {
      let state = this.bizAccountBill.state || 20
      return (+state !== 20)
    }
  },
  mounted () {
    this.formatEntrys()
  },
  methods: {
    formatTime  (item) {
      return `${item.startTime.replace(/-/g, '.')}~${item.endTime.replace(/-/g, '.')}（${countDate(item.endTime, item.startTime) + 1}天）`
    },
    formatEntrys () {
      let entrys = []
      this.bizAccountBill.entrys.forEach((item, index) => {
        let { startTime, vehicle, endTime, expenseType, from, to, expenseTypeName, expenseTypeNumber } = item
        item.travelPerson.forEach((item1, index1) => {
          let { companyName, companyNumber, depNumber, depName, userNum, userName } = item1
          if (from && to && startTime && endTime && endTime && item.travelPerson.length > 0) {
            entrys.push({ vehicle, startTime, endTime, expenseType, expenseTypeName, expenseTypeNumber, from, to, companyName, companyNumber, depNumber, depName, userNum, userName })
          }
        })
      })
      this.entrys = entrys
      this.entrys.forEach((item, index) => {
        this.getTravelTripStandards(index)
      })
    },
    selectCompanyCallBack (data) {
      let index = data.index
      this.entrys[index] = Object.assign({}, this.entrys[index], data)
    },
    selectDepCallBack (data) {
      let index = data.index
      this.entrys[index] = Object.assign({}, this.entrys[index], data)
    },
    selectCompany (index) {
      if (this.readonly) return
      this.$router.push({
        path: '/xinCenStep3/selectCompany',
        query: {
          from: 'xinCenStep3',
          index
        }
      })
    },
    selectDep (index) {
      if (this.readonly) return
      let companyNum = this.entrys[index].companyNumber
      this.$router.push({
        path: '/xinCenStep3/selectDep',
        query: {
          from: 'xinCenStep3',
          index,
          companyNum
        }
      })
    },
    getTravelTripStandards (index) {
      let entry = this.entrys[index]
      getTravelTripStandards({
        userNum: entry.userNum
      }, data => {
        let to = entry.to.substring(0, 2)
        // 住宿标准
        let HotelExpense
        // 出差补助标准交流 50 其他 100
        let EventionSubsidy = 100
        // 出差类型 业务差旅 交流 境外考察
        let expenseTypeName = this.bizAccountBill.expenseTypeName
        if (to === '广州') {
          HotelExpense = data.zhuSuGZ
        } else if (to === '北京' || to === '上海') {
          HotelExpense = data.zhuSuBJSH
        } else {
          HotelExpense = data.zhuSuQT
        }
        let countDay = countDate(entry.endTime, entry.startTime)
        // 计算住宿标准
        this.entrys[index].HotelExpense = HotelExpense * countDay
        this.entrys[index].MaxZSBZ = this.entrys[index].HotelExpense
        // 计算出差标准 交流费不分10天内和10天外 其他分10天内和10天外
        if (expenseTypeName.indexOf('交流') > -1) {
          EventionSubsidy = 50
          this.entrys[index].EventionSubsidy = (countDay + 1) * EventionSubsidy
          this.entrys[index].MaxCCBZ = this.entrys[index].EventionSubsidy
        } else {
          EventionSubsidy = 100
          if (countDay < 10) {
            this.entrys[index].EventionSubsidy = (countDay + 1) * EventionSubsidy
          } else {
            this.entrys[index].EventionSubsidy = 10 * EventionSubsidy + (countDay + 1 - 10) * (EventionSubsidy / 2)
          }
          if (expenseTypeName.indexOf('业务') > -1) {
            this.entrys[index].MaxCCBZ = this.entrys[index].EventionSubsidy
          } else if (expenseTypeName.indexOf('境外') > -1) {
            this.entrys[index].MaxCCBZ = 1000000000000
          }
        }
        this.$forceUpdate()
      })
    },
    handleSubmit (isSubmit) {
      if (+this.bizAccountBill.state === 25) {
        this.initK2()
        return
      }
      let { eveNum, cause } = this.bizAccountBill
      // let isSubmit = 1 // eveNum ? 1 : 0
      let isAllComplete = true
      let entrys = this.entrys.map(item => {
        let { EventionSubsidy, HotelExpense, expenseType, userNum, startTime, endTime, from, to, companyNumber, depNumber, vehicle } = item
        if (!companyNumber || !depNumber || !EventionSubsidy || !HotelExpense) {
          isAllComplete = false
        }
        return { travelPerson: userNum, EventionSubsidy, HotelExpense, expenseType, startTime, endTime, from, to, companyNumber, depNumber, vehicle }
      })

      if (!isAllComplete) {
        this.$tools.openToast({
          msg: '请先完善行程信息',
          duration: 2000
        })
        return
      }

      this.$http({
        url: this.$config.api.host,
        data: {
          method: 'EvectionReqSave',
          EvectionReq: {
            isFromApp: '2',
            biller: this.userNum,
            eveNum,
            isSubmit,
            cause,
            entrys
          }
        }
      }).then(res => {
        if (res.code === 200) {
          this.$store.commit('bizAccountBill', {
            eveNum: res.number,
            evefid: res.evefid
          })
          if (isSubmit === 0) {
            this.$store.commit('bizAccountBill', {
              state: 20
            })
            this.$tools.openToast({
              msg: '暂存成功',
              duration: 2000
            })
          } else {
            this.$store.commit('bizAccountBill', {
              state: 25
            })
            this.initK2()
          }
        }
      })
    },
    initK2 () {
      let billNum = this.bizAccountBill.eveNum
      let JM = getJMByBillNum(billNum)
      let billConfig = getBillConfig()
      let k2Data = {}
      k2Data.billNum = billNum
      k2Data.BOID = this.bizAccountBill.evefid
      k2Data.BSID = billConfig[JM].BSID
      k2Data.ExpenseType = this.bizAccountBill.expenseTypeNumber
      k2Data.sCapital = '0' // this.bizAccountBill.amount
      k2Data.sProcessSubject = this.userInfo.userName + '_' + this.bizAccountBill.expenseTypeName + '_' + billConfig[JM]['title']
      // 获取bodysJson
      let now = new Date()
      let nowDate = formatDate(now, 'yyyy-MM-dd')
      let timeCope = formatDate(new Date(now.setMonth(now.getMonth() + 4)), 'yyyy-MM-dd')
      k2Data.bodysJson = this.bodysJson({
        title: k2Data.sProcessSubject,
        cause: this.bizAccountBill.cause,
        billNum: billNum,
        userName: this.userInfo.userName,
        entrys: this.entrys,
        companyName: this.entrys[0].companyName,
        nowDate,
        timeCope
      })
      sessionStorage.setItem('k2Data', JSON.stringify(k2Data))
      this.$router.push('/sendK2')
    },
    bodysJson (data) {
      console.log(data)
      let {
        title,
        cause,
        billNum,
        userName,
        companyName,
        nowDate,
        timeCope, // 当前时间的后四个月
        entrys
      } = data
      let tabStr = ''

      entrys.forEach(item => {
        tabStr += '<tr><td>' + item.expenseTypeName +
          '</td><td>' + item.userName +
          '</td><td>' + item.startTime +
          '</td><td>' + item.endTime +
          '</td><td>' + item.from +
          '</td><td>' + item.to +
          '</td><td>' + item.companyName +
          '</td><td>' + item.depName +
          '</td></tr>'
      })

      let jsonStr = `<style type='text/css'>
        .menuBar { display: inline-block; background: #e6e6e6; } .menuBar ul { list-style: none; } .menuBar li { float: left; width: 100px; margin-left: 3px; line-height: 30px; } .menuBar a { display: block; text-align: center; height: 30px; } .menuBar a:link { color: red; font-weight: bold; text-decoration: none; background: #e6e6e6; } .menuBar a:visited { color: red; font-weight: bold; text-decoration: none; background: #e6e6e6; } .menuBar a:hover { color: green; font-weight: bold; text-decoration: none; background: #e6e6e6; } #base { background-color: #e6e6e6; } .panel { font-size: 12px; text-align: left; margin-top: 7px; } .panel.sheader { padding-top: 5px; } .panel.sheader.titile { color: blue; font-weight: bold; } .panel.content { padding-top: 5px; } .panel.content.block { width: 100%; position: relative; margin-top: 10px; } .panel.content.leftBlock { width: 50%; float: left; vertical-align: top; } .panel.content.rightBlock { width: 49%; float: right; vertical-align: top; } .ui-lablecontainer { padding-bottom: 5px; padding-top: 0px; padding-left: 0px; padding-right: 0px; margin: 0px 10px; } .ui-lablecontainer.label { width: 100px; display: inline-block; vertical-align: middle; } .ui-lablecontainer.value { display: inline-block; vertical-align: middle; overflow: hidden; } div { word-wrap: break-word; word-break: normal; }
        </style>
        <div class='main'> <div class='panel' id='topic'> <div class='sheader'> <span class='titile'><a onclick='showdiv(1)'>+主题</a></span></div> <div class='contents' id='contentPane1' style='color: red; font-size: 16px; font-weight: bold;'> <div class='block'> <div class='ui-lablecontainer' id='topic'> <label class='label'> <span></span> </label> <span class='value'>
        ${title}</span></div> </div> </div> </div> <div class='panel' id='cause'> <div class='sheader'> <span class='titile'><a onclick='showdiv(3)'>+事由</a></span></div> <div class='contents' id='contentPane3' style='color: red; font-size: 16px; font-weight: bold;'> <div class='block'> <div class='ui-lablecontainer' id='cause'> <label class='label'> <span></span> </label> <span class='value'> <table style='width: 650px;'> <tbody> <tr> <td style='color: red; font-size: 16px; font-weight: bold; -ms-word-break: break-all;'>
        ${cause}</td> </tr> </tbody> </table> </span> </div> </div> </div> </div> <div class='panel' id='base'> <div class='sheader'> <span class='titile'><a onclick='showdiv(2)'>+基本信息</a></span></div> <div class='contents' id='contentPane2'> <div class='block'> <div class='leftBlock'> <div class='ui-lablecontainer' id='number'> <label class='label'> <span>单据编号:</span></label><span class='value'>
        ${billNum}</span></div> <div class='ui-lablecontainer' id='applier'> <label class='label'> <span>申请人:</span></label><span class='value'>
        ${userName}</span></div> <div class='ui-lablecontainer' id='applierCompany'> <label class='label'> <span>申请公司:</span></label><span class='value'>
        ${companyName}</span></div> </div> <div class='rightBlock'> <div class='ui-lablecontainer' id='bizReqDate'> <label class='label'> <span>申请日期:</span></label><span class='value'>
        ${nowDate}</span></div> <div class='ui-lablecontainer' id='effecDate'> <label class='label'> <span>有效日期:</span></label><span class='value'>
        ${timeCope}</span></div> </div> </div> </div> </div> <div class='panel' id='entry'> <div class='sheader'> <span class='titile'><a onclick='showdiv(4)'>+行程清单</a></span></div> <div class='contents' id='contentPane4'> <div class='block'> <table width='100%' border='1'> <tbody> <tr> <td> 费用类型 </td> <td> 出差人 </td> <td> 开始日期 </td> <td> 结束日期 </td> <td> 出发地点 </td> <td> 目的地点 </td> <td> 预算（额度）归属公司 </td> <td> 预算（额度）归属部门 </td> </tr>
        ${tabStr}</tbody> </table> </div> </div> </div> <div class='panel' id='billInfo'> <div class='sheader'> <span class='titile'><a onclick='showdiv(5)'>+制单信息</a></span></div> <div class='contents' id='contentPane5'> <div class='block'> <div class='leftBlock'> <div class='ui-lablecontainer' id='biller'> <label class='label'> <span>制单人:</span></label><span class='value'>
        ${userName}</span></div> </div> <div class='rightBlock'> <div class='ui-lablecontainer' id='billDate'> <label class='label'> <span>制单日期:</span></label><span class='value'>
        ${nowDate}</span></div> </div> </div> </div> </div></div>`
      console.log(jsonStr)
      return jsonStr
    },
    abandonNewBills () {
      abandonNewBills(this.bizAccountBill.eveNum, () => {
        this.$store.commit('resetBizAccountBill')
        this.$router.replace('/')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/config';
@import '../assets/css/mixins';
.content{
  padding-bottom:1.3rem;
}
.item{
  width:90%;
  margin: 0 auto;
  margin-top:.3rem;
  background-color:#FFF;
  border-radius:.2rem;
  overflow: hidden;
  .head{
    height:1.1rem;
    font-size:.48rem;
    line-height:1.1rem;
    padding:0 .3rem;
    color:#FFF;
    background-color:$themeColor;
    .city{
      font-size:.36rem;
    }
  }
  .line{
    line-height: .8rem;
    height:.8rem;
    padding: 0 .3rem;
    border-bottom:1px solid $borderColor;
  }
  .icon-edit{
    margin-left:.1rem;
    width:.36rem;
    height:.36rem;
  }
}
.bottom{
  position:absolute;
  bottom:0;
  width:100%;
  background-color: $themeColor;
  height:1rem;
  font-size:.36rem;
  .btn{
    color:#FFF;
    height:100%;
    &:nth-of-type(2){
      color:$themeColor;
      background-color:#FFF;
    }
  }
}
// .btn-bot{
//   @include btn(100%, 1rem, .36rem);
// }
</style>
